﻿using AutoMapper;
using Cache.CSRedis;
using EventBus.Common;
using Microsoft.EntityFrameworkCore.Internal;
using Order.Common;
using Order.Common.Command;
using Order.Common.IntegratedEvent;
using Order.Common.Logger;
using Order.Common.WebApiClient;
using Order.Domain.DomainService;
using Order.Domain.Entity;
using Order.Domain.Repository;
using Order.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ILoggerHelper = Order.Common.Logger.ILoggerHelper;

namespace Order.CommandHandler
{
    public class OrderCommandHandler : ICommandHandler<CreateOrderCommand>
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRedisHelper _redisHelper;
        private readonly ILoggerHelper _loggerHelper;
        private readonly IntegratedEventService _integratedEventService;
        private readonly IMapper _mapper;
        private readonly VerifySkuService _verifySkuService;
        private readonly VerifyCustomerService _verifyCustomerService;
        private readonly CreateOrderService _createOrderService;
        private readonly ISkuApi _skuApi;
        public OrderCommandHandler(
            ILoggerHelper loggerHelper,
            IOrderRepository orderRepository,
            IUnitOfWork unitOfWork,
            IRedisHelper redisHelper,
            IntegratedEventService integratedEventService,
            IMapper mapper,
            VerifySkuService verifySkuService,
            VerifyCustomerService verifyCustomerService,
            CreateOrderService createOrderService,
            ISkuApi skuApi)
        {
            _unitOfWork = unitOfWork;
            _redisHelper = redisHelper;
            _orderRepository = orderRepository;
            _loggerHelper = loggerHelper;
            _integratedEventService = integratedEventService;
            _mapper = mapper;
            _verifySkuService = verifySkuService;
            _verifyCustomerService = verifyCustomerService;
            _createOrderService = createOrderService;
            _skuApi = skuApi;
        }
        public async Task HandleAsync(CreateOrderCommand command)
        {
            try
            {
                List<OrderItem> orderItemList = new List<OrderItem>();
                foreach (var sku in command.SkuList)
                {
                    var orderItem = new OrderItem().SetOrderItem(sku.SkuPrice, sku.SkuQuantity, sku.SkuId, sku.SpuName);
                    orderItemList.Add(orderItem);
                }

                //验证sku的有效性
                var verifySkuResultMsg = await VerifySku(orderItemList);

                //验证客户的有效性
                var verifyCustomerResultMsg = await _verifyCustomerService.VerifyCustomer();

                //生成订单号，创建订单，扣减库存
                var result = await CreateOrderAsync(command.CustomerId, orderItemList);
            }
            catch (Exception ex)
            {
                _loggerHelper.LogInfo("CreateOrderByCommandEvent方法异常", ex.Message);
            }
        }

        /// <summary>
        /// 验证sku的有效性
        /// </summary>
        /// <returns></returns>
        public async Task<string> VerifySku(List<OrderItem> orderItemList)
        {
            var resultMsg = string.Empty;
            //验证sku的有效性
            var verifySkuResult = await _skuApi.GetVerifySkuDto(orderItemList.Select(e => e.SkuId).Join(","));
            if (verifySkuResult.IsSucceed)
            {
                var verifySkuResultMsg = await _verifySkuService.VerifySku(verifySkuResult.Result, orderItemList);
                if (!string.IsNullOrWhiteSpace(verifySkuResultMsg))
                {
                    resultMsg = verifySkuResultMsg;
                }
            }
            return resultMsg;
        }

        /// <summary>
        /// 持久化订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<ResponseResult<string>> CreateOrderAsync(string customerId, List<OrderItem> orderItemList)
        {
            var orderNo = await _createOrderService.CreateOrder(customerId, orderItemList);
            var isTrue = await _unitOfWork.CommitAsync();
            if (isTrue)
            {
                return new ResponseResult<string> { IsSucceed = true, Message = orderNo };
            }
            else
            {
                return new ResponseResult<string> { IsSucceed = false, Message = $"订单号：{orderNo},存储失败！" };
            }
        }


        /// <summary>
        /// 扣减库存
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task<string> DeductionRedisStock()
        {
            var errMessage = string.Empty;
            try
            {
                var script = @"local stock = redis.call('get', KEYS[1]) 
                             if stock == '0' then
                              return 0;
                             end
                              redis.call('decr', KEYS[1])
                              return 1";
                var remainderProductStock = _redisHelper.Lua(script, "ProductStock");
                if (remainderProductStock == 0)
                {
                    errMessage = "库存不足,抢购失败！";
                }
            }
            catch (Exception ex)
            {
                errMessage = $"扣减库存异常！原因：{ex.Message}";
            }
            return errMessage;
            await Task.CompletedTask;
        }
                   
    }
}
